import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/sqlite_db';

export async function POST(req: NextRequest) {
  try {
    const data = await req.json();
    const configEntries = Object.entries(data);

    for (const [key, config] of configEntries) {
      if (!['model_for_form', 'model_for_code', 'model_for_document', 'model_for_prompt_expert'].includes(key)) {
        continue;
      }

      // 过滤掉api_key为空的情况
      if (typeof config === 'object' && config !== null && !config.api_key) {
        // 如果api_key为空，不更新该配置
        continue;
      }

      const configValue = JSON.stringify(config);

      // 检查是否已存在该配置
      const checkSql = `SELECT * FROM admin_config WHERE config_key = ?`;
      const existingConfig = await query(checkSql, [key]);

      if (existingConfig && existingConfig.length > 0) {
        // 更新现有配置
        const updateSql = `
          UPDATE admin_config
          SET config_value = ?
          WHERE config_key = ?
        `;
        await query(updateSql, [configValue, key]);
      } else {
        // 创建新配置
        const insertSql = `
          INSERT INTO admin_config (config_key, config_value)
          VALUES (?, ?)
        `;
        await query(insertSql, [key, configValue]);
      }
    }

    return NextResponse.json({
      success: true,
      message: '配置保存成功',
    });
  } catch (error) {
    console.error('保存模型配置失败:', error);
    return NextResponse.json({
      success: false,
      message: '保存配置失败',
      error: String(error),
    }, {
      status: 500,
    });
  }
}

export async function GET() {
  const defaultConfig = {
    api_url: 'https://open.bigmodel.cn/api/paas/v4/chat/completions',
    api_key: '',
    model_name: 'glm-4',
  };

  try {
    const sql = `
      SELECT config_key, config_value
      FROM admin_config
      WHERE config_key IN (
        'model_for_form',
        'model_for_code',
        'model_for_document',
        'model_for_prompt_expert'
      )
    `;
    const configs = await query(sql);

    const result: Record<string, any> = {
      model_for_form: defaultConfig,
      model_for_code: defaultConfig,
      model_for_document: defaultConfig,
      model_for_prompt_expert: defaultConfig,
    };

    configs.forEach(config => {
      try {
        result[config.config_key] = JSON.parse(config.config_value);
      } catch (error) {
        console.error(`解析配置 ${config.config_key} 失败:`, error);
      }
    });

    return NextResponse.json({ data: result });
  } catch (error) {
    console.error('获取模型配置失败:', error);
    return NextResponse.json({ 
      data: {
        model_for_form: defaultConfig,
        model_for_code: defaultConfig,
        model_for_document: defaultConfig,
        model_for_prompt_expert: defaultConfig,
      },
      error: '获取配置失败' 
    }, { status: 500 });
  }
}